package com.moyv.schoolbbs.service;

import android.os.Handler;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;
import static com.moyv.schoolbbs.config.URLConstant.LOGIN_URL;
import static com.moyv.schoolbbs.config.URLConstant.REGISTER_URL;
import static com.moyv.schoolbbs.util.HttpUtil.createClient;
import static com.moyv.schoolbbs.util.ToastUtils.show;

/**
 * @author moyv
 */
public class RegisterService {
    public void register(int account, String name, String password, Handler handler) {
        String url = REGISTER_URL;
        OkHttpClient okHttpClient = createClient();
        JSONObject obj = new JSONObject();
        try {
            obj.put("account", account);
            obj.put("name", name);
            obj.put("password", password);
        } catch (JSONException e) {
            Log.d(TAG, "getPost: json添加失败");
        }
        FormBody formBody = new FormBody.Builder()
                .add("request", obj.toString())
                .build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("Register.register:连接服务器失败");
                handler.sendMessage(handler.obtainMessage(500));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("Register.register:连接服务器成功");
                String responseData = response.body().string();
                int result = 0;
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    result = jsonObject.getInt("result");
                } catch (JSONException e) {
                    show("注册后返回数据解析失败");
                }
                switch (result) {
                    case 0:
                        handler.sendMessage(handler.obtainMessage(500));
                        break;
                    case 1:
                        handler.sendMessage(handler.obtainMessage(200));
                        break;
                    case 2:
                        handler.sendMessage(handler.obtainMessage(301));
                        break;
                    case 3:
                        handler.sendMessage(handler.obtainMessage(302));
                        break;
                    default:

                }
            }
        });
    }
}
